package com.base.controller.coupon_api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.controller.api.RedisCacheManager;
import com.base.helper.VosHelper;
import com.base.helper.WebHelper;
import com.base.po.coupon_new.CouponGoodsNew;
import com.base.po.coupon_new.CouponOrderNew;
import com.base.po.coupon_new.CouponOrderNewSub;
import com.base.po.coupon_sdk.AesUtil;
import com.base.po.coupon_sdk.CouponAESUtil;
import com.base.po.coupon_sdk.CouponConfigNew;
import com.base.po.param.VosModelList;
import com.base.po.voip.ChangeRecord;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.service.COUPON.CouponGoodsNewService;
import com.base.service.COUPON.CouponOrderNewService;
import com.base.service.COUPON.CouponOrderNewSubService;
import com.base.service.ChangeRecordService;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.DateUtil;
import com.base.utils.GsonUtil;
import com.base.utils.Produce;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Log4j
@RestController
@RequestMapping("/haiwei")
public class HaiWeiCallBack {
    private final CouponOrderNewService couponOrderNewService;
    private final CouponOrderNewSubService couponOrderNewSubService;
    private final RedisCacheManager redisCacheManager;
    private final SubscribersService subscribersService;
    private final UsersService usersService;
    private final CouponGoodsNewService couponGoodsNewService;
    private final ChangeRecordService changeRecordService;

    @Autowired
    public HaiWeiCallBack(CouponOrderNewService couponOrderNewService, CouponOrderNewSubService couponOrderNewSubService, RedisCacheManager redisCacheManager, SubscribersService subscribersService, UsersService usersService, CouponGoodsNewService couponGoodsNewService, ChangeRecordService changeRecordService) {
        this.couponOrderNewService = couponOrderNewService;
        this.couponOrderNewSubService = couponOrderNewSubService;
        this.redisCacheManager = redisCacheManager;
        this.subscribersService = subscribersService;
        this.usersService = usersService;
        this.couponGoodsNewService = couponGoodsNewService;
        this.changeRecordService = changeRecordService;
    }

    /*
       1.接受到订单就把参数放到数据库之中
       2.recordUserBuy之前记录的用户购买海威产品的用户信息（通过orderNo进行对比）
       3.存入我们的订单信息
       4.订单可能是存在单一单对应多个小订单（两张表进行关联）
       5.如果是code为200则表示正常支付，就扣款（话费）

    */
    @RequestMapping("/getPayBack")
    public String getPayBack(String transaction_id,String code,String batch_no,String brand_name,String commodity_name,String total_amount,String platform_batch_no,String data,String goods_no,String count,String sign ) throws UnsupportedEncodingException, ParseException {
        log.warn("[海威回调]"+batch_no);
        if (StringUtils.isEmpty(batch_no)){
            return "success";
        }
       CouponOrderNew couponOrderNew=couponOrderNewService.selectByPlatformBatchNo(batch_no);
        if (couponOrderNew == null){
//            redisCacheManager.get
            BigDecimal commoney=total_amount == null?new BigDecimal(0):new BigDecimal(total_amount);
            couponOrderNew=new CouponOrderNew(batch_no, platform_batch_no,brand_name, commodity_name,goods_no, transaction_id,  Integer.parseInt(count),commoney , null, null, 1);

            CouponAESUtil aesUtil = new CouponAESUtil();
            String resultData = aesUtil.decrypt(data, CouponConfigNew.SECRET_KEY);
            JSONArray jsonArray=JSONArray.parseArray(resultData);
            Object userid=redisCacheManager.get("QY:"+couponOrderNew.getBatchNo());
            if (userid!=null){
                Subscribers subscribers= subscribersService.selectByPrimaryKey(userid.toString());
                CouponGoodsNew couponGoodsNew=couponGoodsNewService.selectCouponGoodsNewByGoodsNo(couponOrderNew.getGoodsNo());
                BigDecimal money = new BigDecimal(0);
                money=couponGoodsNew.getOfficialPrice().subtract(couponGoodsNew.getSellPrice());
                if (subscribers.getParentid().equals("24bc36812eed4772ae7a18efab0e3048")){
                    log.warn("旅享生活扣费");
                    String url="http://www.tralife.cn/oiling_api.asp?phone="+subscribers.getMobile()+"&amount="+couponOrderNew.getTotalAmount()+"&jifen="+money;
                    String result2= WebHelper.GetData(url,null);
                    log.warn("[旅享生活扣费] mobile="+subscribers.getMobile()+"接口返回值"+result2);

                }else{

                    if (subscribers!=null){
                        couponOrderNew.setParentid(subscribers.getParentid());
                        couponOrderNew.setMobile(subscribers.getMobile());

                        Users agent=usersService.selectByPrimaryKey(subscribers.getParentid());
                        Subscribers user=subscribers;
                        // 查询变更前话费余额
                        BigDecimal beforeB = new BigDecimal(0);
                        // 备注
                        String remark = null;
                        try {
                            // TODO 暂时配注
                            String userR = VosHelper
                                    .GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
                            if (userR != null) {
                                VosModelList shareUserR1 = GsonUtil.getObject(userR, VosModelList.class);
                                if (shareUserR1.retCode == 0) {
                                    beforeB = shareUserR1.infoCustomers[0].getMoney();
                                } else {
                                    beforeB = new BigDecimal(0);
                                    remark = "暂无记录";
                                }
                            }
                        } catch (Exception e) {
                            beforeB = new BigDecimal(0);
                            remark = "暂无记录";
                        }
                        // 查询变更前话费有效期
                        Date beforeTimeB = user.getEndtime();
                        // 查询变更话费
                        BigDecimal changeB = new BigDecimal(0);
                        // 查询变更话费有效期
                        Date changeTimeB = new Date();
                        // 查询变更前购物金余额
                        BigDecimal beforeS = BigDecimal.valueOf(user.getShopBalance());
                        // 查询变更前购物金有效期
                        Date beforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
                                .parse(user.getShopEnddate());
                        // 查询变更购物金
                        BigDecimal changeS = new BigDecimal(0);
                        // 查询变更购物金有效期
                        Date changeTimeS = new Date();

                        Date daydate = Produce.getNowDate(); // 当前时间



                        if (couponGoodsNew != null){

                            money = money.multiply(new BigDecimal(-1));
                            log.warn("准备扣钱:" + couponOrderNew.getBatchNo());
                            String result1 = VosHelper.GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
                            VosModelList v1 = GsonUtil.getObject(result1, VosModelList.class);

                            for (int i = 0; i <jsonArray.size() ; i++) {
                                if (agent.equals("13715e2af9b24f55ab24773101688490")){
                                    //不做处理  如果是团拼宝
                                }else{
                                    //执行扣除话费
                                    String payinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix() + user.getMobile()
                                            + "\",\"ownerType\":\"2\",\"money\":\"" + money + "\",\"memo\":\"" + user.getUsername()
                                            + "，用户购买优惠券" + money + "元\"}");

                                    changeB = money;
                                    changeRecordService.insertSelective(new ChangeRecord(user.getParentid(), user.getShopid(),
                                            user.getId(), Produce.getNowDate(), beforeB, changeB, 0, beforeTimeB, changeTimeB, "购买优惠券扣款",
                                            beforeS, changeS, 0, beforeTimeS, changeTimeS, "购买优惠券", remark));
                                }

                            }


                        }
                    }
                }

            }
            couponOrderNewService.insertSelective(couponOrderNew);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject orderSubStr=jsonArray.getJSONObject(i);
                String orderno=orderSubStr.getString("order_no");
                log.warn("[海威订单回调OrderNo：]"+orderno);
                String etime=orderSubStr.getString("effective_time");
                Integer order_status=orderSubStr.getString("order_status") == null? 0:Integer.parseInt(orderSubStr.getString("order_status"));
                BigDecimal payamout=orderSubStr.getString("pay_amount") == null ?new BigDecimal(0):new BigDecimal(orderSubStr.getString("pay_amount"));
                String ticket_code=orderSubStr.getString("ticket_code");
                Integer code_type=orderSubStr.getString("code_type") == null ?0 :Integer.parseInt(orderSubStr.getString("code_type")) ;
                Integer goods_type=orderSubStr.getString("goods_type") == null? 0:Integer.parseInt(orderSubStr.getString("goods_type"));
                String card_no=orderSubStr.getString("card_no");
                String card_password=orderSubStr.getString("card_password");
                BigDecimal commission=orderSubStr.getString("commission") == null ?new BigDecimal(0):new BigDecimal(orderSubStr.getString("commission"));
                Date effective_time=null;
                if (!StringUtils.isEmpty(etime)){
                    try{
                        effective_time= DateUtil.strToDate2(etime);
                    }catch (Exception e){
                        log.error(e);
                    }
                }
                //数据收集完毕

                CouponOrderNewSub couponOrderNewSub=new CouponOrderNewSub( orderno, effective_time, order_status,payamout, ticket_code, code_type, goods_type, card_no, card_password, commission,batch_no);

//                CouponOrderNewSub consSql= couponOrderNewSubService.selectByPl
//                if (consSql==null){
                    couponOrderNewSubService.insertSelective(couponOrderNewSub);
//                }else{
//                    couponOrderNewSub.setId(consSql.getId());
//                    couponOrderNewSubService.updateByPrimaryKeySelective(couponOrderNewSub);
//                }
            }
        }
        log.warn("[海威回调] 成功");
        return "success";
    }

    @RequestMapping("/changePayOrder")
    public String changePayOrder(Integer code,String data,String message,String time_stamp,String sign)  {
        log.warn("[海威状态变更信息]"+code+":"+data+":"+message+":"+time_stamp+":"+sign);
       try{
           AesUtil asUtil=new AesUtil();
           String resultData=null;
           try {
                resultData= asUtil.decrypt(data,CouponConfigNew.SECRET_KEY);
               System.out.println(resultData);
           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           }
           if (resultData==null){
               log.error("解码失败");
           }
//           String resultData = aesUtil.decrypt(bTemp, CouponConfigNew.SECRET_KEY);
           JSONObject jsonObject=JSONObject.parseObject(resultData);
           String order_no=jsonObject.getString("order_no");
           String orderStatus=jsonObject.getString("order_status");
           CouponOrderNewSub couponOrderNew=couponOrderNewSubService.selectByOrderNo(order_no);
           if (couponOrderNew == null ){
               return "success";
           }
           couponOrderNew.setOrderStatus(Integer.parseInt(orderStatus));
           couponOrderNewSubService.updateByPrimaryKeySelective(couponOrderNew);
           return "success";
       }catch (Exception e){
           log.warn(e);
       }finally {
           return "success";
       }

    }
}
